import { useEffect, useState } from "react";
import { useComponentsStore } from "@/stores/edit-pages-store";
import MonacoEditor, { OnMount } from "@monaco-editor/react";
import { omit } from "lodash-es";

export interface CustomJSConfig {
  type: "customJS";
  label: string;
  code: string;
}

interface CustomJSProps {
  value?: string;
  defaultValue?: string;
  onChange?: (config: CustomJSConfig) => void;
}
export const customJSMsg = {
  type: "customJS",
  label: "自定义JS",
  desc: "通过JavaScript自定义动作逻辑"
};

export function CustomJS(props: CustomJSProps) {
  const { value: val, defaultValue, onChange } = props;

  const { curComponentId } = useComponentsStore();
  const [value, setValue] = useState(defaultValue);

  useEffect(() => {
    if (val) {
      setValue(val);
    }
  }, [val]);

  function codeChange(value?: string) {
    if (!curComponentId) return;

    setValue(value);

    onChange?.({
      ...omit(customJSMsg,'desc') as Omit<CustomJSConfig, "code">,
      code: value!,
    });
  }

  const handleEditorMount: OnMount = (editor, monaco) => {
    editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyJ, () => {
      editor.getAction("editor.action.formatDocument")?.run();
    });
  };

  return (
    <div className="h-full flex flex-col p-4 ">
      <div>自定义 JS</div>
      <div className="border border-blue-500">
        <MonacoEditor
          height={"300px"}
          // width={"600px"}
          // height={"100%"}
          path="action.js"
          language="javascript"
          onMount={handleEditorMount}
          onChange={codeChange}
          value={value}
          options={{
            fontSize: 14,
            scrollBeyondLastLine: false,
            minimap: {
              enabled: false,
            },
            scrollbar: {
              verticalScrollbarSize: 6,
              horizontalScrollbarSize: 6,
            },
          }}
        />
      </div>
    </div>
  );
}
